import com.khh.entity.Student;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import org.junit.Test;

import java.util.List;

/**
 * Created by webrx on 2017-09-14.
 */
public class Demo {


    //hql增删改查
    @Test
    public void a(){
        Configuration cfg = new Configuration().configure();
        SessionFactory sf = cfg.buildSessionFactory();
        Session session = sf.openSession();
        //开启事务
        session.beginTransaction();

        //添加数据 此方法5.2.x之后才有
        /*NativeQuery query = session.createQuery("insert into student values(:name,:age,:score)");
        query.setParameter("age",50);
        query.setParameter("name","html5");
        query.setParameter("score","88");
        int i = query.executeUpdate();
        System.out.println(i);*/

        //删除byid  1.三中写法相同
       /* Query query = session.createQuery("delete Student where id=:id");
        query.setParameter("id",3);
        int i = query.executeUpdate();
        System.out.println(i);*/
        /*Query query1 = session.createQuery("delete from Student where id=:id");
        Query query2 = session.createQuery("delete from Student where id=?");
        query2.setParameter("0",3);
        int i = query2.executeUpdate();
        System.out.println(i);*/


        //查询数据
        /*Query query = session.createQuery("from Student");
        List<Student> b = query.list();
        System.out.println(b.size());*/


        //提交事务
        session.getTransaction().commit();
    }

    //基本增删改查
    @Test
    public void m(){
        Configuration cfg = new Configuration().configure();
        SessionFactory sf = cfg.buildSessionFactory();
        Session session = sf.openSession();

        //开启事务
        session.beginTransaction();

        //插入数据
        Student s = new Student();
        s.setAge(20);
        s.setName("小明");
        s.setScore(99);
        //插入数据
        session.save(s);

        //查询所有
        /*List<Student> list = session.createQuery("from Student").list();
        System.out.println(list.size());
        for(Student b : list){
            System.out.println(b.getName());
        }*/


        //更新数据byid
        /*Student book = session.get(Student.class,2);
        book.setName("jack");
        book.setAge(20);
        session.saveOrUpdate(book);*/


        //删除数据byid
        //session.delete(session.load(Student.class,2));

        //提交事务
        session.getTransaction().commit();
    }

}
